TypeScript实践—关于json 等非js文件的导入

有一个需要使用TypeScript 重构的项目,开始学习并研究TypeScript,并记录在此过程中遇到的一些问题及解决方式

  • 对于 .json 文件

1、对于 typings 中 声明文件 在项目根目录下 ,与 src 文件夹同级,建立typings 目录

2、对于在ts|tsx文件中引入assets文件,例如 .json|.css|.jpg 文件等,使用原本的

import name from ‘’ 方式行不通,原因是 TypeScript处理模块的方式,于是在官网及网上搜索,找到一些常见的解决方案,

  • 官网推荐

声明文件:

1
2
3
4
5
6
7
8
9
declare module "*!text" {
const content: string;
export default content;
}
// Some do it the other way around.
declare module "json!*" {
const value: any;
export default value;
}

导入

1
2
3
import fileContent from "./xyz.txt!text"; 
import data from "json!http://example.com/data.json"; 允许引入remote URL
console.log(data, fileContent);

官网对于允许导入非js内容的说明

Load a Json File with TypeScript

上一篇中所说的内容 声明文件和引入

1
2
3
4
5
6
7
8
9
10
11
12
13
// This will allow you to load `.json` files from disk

declare module "*.json"
{ const value: any;
export default value;
}

// This will allow you to load JSON from remote URL responses

declare module "json!*"
{ const value: any;
export default value;
}
1
2
import * as graph from './data/graph.json';
import data from "json!http://foo.com/data_returns_json_response/";
  • 方式二
1
const Name = require('../../package.json');

但是相对而言,应当使用官网推荐的,但是我的文件中使用 方式一,有问题,具体还要研究,所以使用的方式二

还有注意的点,

就是需要在 tsconfig.json 中的配置项中加入typings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react",
"experimentalDecorators": true 实验性的装饰器语法使用报错
},
"include": [
"./src/**/*",
"./typings/**/*" 将声明文件也要引入
]
}

require的方式 是不推荐的

终于 我解决的方式:

1.在tsconfig.json 文件中的 include中 引入 声明文件

1
2
3
4
5
6
{
"include": [
"./src/**/*",
"./assets.d.ts"
]
}

2、在声明文件中加入相应的静态文件的 声明

1
declear module "*.json"

3、在需要的地方对非js 的静态资源文件进行引入

1
import * as packageJson from './package.json'

4、使用

1
{packageJson.version}
  • 对于 .css 文件

1、需要在声明文件中,做出声明

1
2
declear module "*.css";
declear module "*.svg"

2、在使用的地方进行引入

1
2
3
import * as logo from './x.svg';
import logo from './x.svg'
import './css.css'

使用

1
<img src = {logo} className = [class]>